package com.douguo.recipe.network;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;

import com.douguo.recipe.RecipelistActivity;
import com.douguo.recipe.object.Caipu;

public class GetPhoto {

	private static List<AsyncTask<Void, Void, Void>> mTasks = new ArrayList<AsyncTask<Void, Void, Void>>();

	// use when the activity is onPause or want to stop the task manually
	public static void stopTasks() {
		for (AsyncTask<Void, Void, Void> task : mTasks) {
			task.cancel(true);
		}
		if (mTasks.size() > 0)
			mTasks.clear();
	}

	public static void getPhoto(final Integer pos, final String picUrl,
			final Handler handler) {

		// new Thread(new Runnable(){
		//
		// public void run() {
		//
		//
		// }
		//
		// }).start();

		class GetPhotoTask extends AsyncTask<Void, Void, Void> {
			boolean isRunning;

			@Override
			protected Void doInBackground(Void... params) {
				isRunning = true;
				DouguoConnection mConn = new DouguoConnection(picUrl, null,
						mParseListener, DouguoConnection.GET_METHOD);
				SoftReference<Bitmap> refBitmap = (SoftReference<Bitmap>) mConn
						.Connect();
				if (isRunning) {
					handler.sendMessage(Message.obtain(handler,
							Constant.GET_PHOTO, pos, 0, refBitmap));
				}
				return null;
			}

			@Override
			protected void onCancelled() {
				isRunning = false;
			}

		}
		AsyncTask task = new GetPhotoTask();
		mTasks.add(task);
		task.execute(null);
	}

	private static OnParseListener mParseListener = new OnParseListener() {

		public Object onParsing(InputStream is) {
			return Util.inputStreamToRefBitmap(is);// SoftReference
		}

	};

}
